<script setup lang="tsx">
import { useTable } from '@/hooks/web/useTable'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useI18n } from '@/hooks/web/useI18n'
import { ActionButtonsTemplate } from '@/api/global/types'
import useSchema from './components/hooks/useSchema'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Search } from '@/components/Search'
import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'
import {
  getEnumApi,
  getListApi,
  exportFileApi,
  saveEditApi
} from '@/api/warehouse/merchandiseOffers'
import DialogImport from './components/DialogImport/index.vue'
import EditDialog from './components/EditDialog.vue'
import Field from './components/field.vue'
import dayjs from 'dayjs'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { ElMessage } from 'element-plus'
import { ArrowDown, ArrowRight } from '@element-plus/icons-vue'

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
defineOptions({
  name: 'MerchandiseOffers'
})

const { push } = useRouter()

const DialogImportRef = ref<InstanceType<typeof DialogImport>>()
const EditDialogRef = ref<InstanceType<typeof EditDialog>>()
const searchRef = ref<InstanceType<typeof Search>>()
const searchParams = ref({})

const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const warehouseList = ref([])
const wid = ref([])
const is_futuresList = ref([])
const currencyList = ref([])

// 为树形数据添加唯一ID和层级标识
const addUniqueIds = (data: any[], parentId = '', level = 0) => {
  return data.map((item, index) => {
    const uniqueId = parentId ? `${parentId}-${index}` : `${level}-${index}`

    // 第一层使用 inventory_id，其他层使用生成的唯一ID
    const nodeId =
      level === 0 && item.inventory_id ? `inv_${item.inventory_id}` : `node_${uniqueId}`

    const processedItem = {
      ...item,
      _nodeId: nodeId, // 添加唯一节点ID
      _level: level // 添加层级标识
    }

    if (item.children && item.children.length > 0) {
      processedItem.children = addUniqueIds(item.children, nodeId, level + 1)
    }

    return processedItem
  })
}

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: true,
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const params = {
      ...unref(searchParams)
    } as Record<string, any>
    if (params.time) {
      params.start_date = `${params.time[0]} 00:00:00`
      params.end_date = `${params.time[1]} 23:59:59`
      delete params.time
    }
    const res = await getListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      type: 2,
      ...params
    })

    // 处理数据，添加唯一ID
    const processedList = addUniqueIds(res.data.list)

    return {
      list: processedList,
      total: res.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

useEventBus({
  name: 'getMerchandiseOffersList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})
const { t } = useI18n()

// 弹窗相关状态
const editDialogVisible = ref(false)
const editData = ref<any>(null)

const handleJumpToEdit = (row: Record<string, any>, type: string) => {
  console.log('row', row)
  editData.value = {
    id: row.productid,
    wid: row.warehouse_id,
    fl_warehouse_id: row.fl_warehouse_id,
    warehouseName: row.warehouse_name,
    hashrate: row.hashrate,
    cname: row.cname,
    product_code: row.product_code,
    time: row.arrival_date,
    quantity: row.quantity,
    arrival_date: row.arrival_date,
    real_arrival_date: row.real_arrival_date,
    is_futures_text: useEnumeratePicker(is_futuresList.value, row.is_futures),
    is_futures: row.is_futures
  }
  editDialogVisible.value = true
}

// 编辑成功回调
const handleEditSuccess = () => {
  getList() // 刷新列表
}

const actionButtonsTemplate: ActionButtonsTemplate = {
  length: 3,
  template: (data: any) => {
    return (
      <>
        <BaseButton
          size="small"
          onClick={() => handleJumpToEdit(data.row, 'merchandiseOffersEdit')}
        >
          编辑
        </BaseButton>
      </>
    )
  }
}

const allSchemas = ref<Record<string, any>>({})

const getSelectList = async () => {
  const resp = await getEnumApi({ field: 'all' })
  warehouseList.value = resp.data.warehouse_parent_tree
  wid.value = resp.data.wid
  is_futuresList.value = resp.data.is_futures
  currencyList.value = resp.data.currency

  const { crudSchemas } = useSchema({
    actionButtonsTemplate,
    warehouseList: warehouseList.value,
    is_futuresList: is_futuresList.value,
    currencyList: currencyList.value,
    wid: wid.value
  })
  const { allSchemas: schemas } = useCrudSchemas(crudSchemas)
  allSchemas.value = schemas
}

getSelectList()

const handleImport = () => {
  nextTick(() => {
    DialogImportRef!.value!.dialogVisible = true
  })
}

const handleExport = () => {
  nextTick(async () => {
    const { currentPage, pageSize } = tableState
    const searchParamsForm = await searchRef.value!.filterModel()
    const params = {
      ...unref(searchParamsForm)
    } as Record<string, any>
    if (params.time) {
      params.start_date = `${params.time[0]} 00:00:00`
      params.end_date = `${params.time[1]} 23:59:59`
      delete params.time
    }
    await exportFileApi(
      {
        pageIndex: unref(currentPage),
        pageSize: unref(pageSize),
        type: 2,
        ...unref(params)
      },
      `商品报价_${dayjs().format('YYYY.MM.DD')}.xlsx`
    )
  })
}

const handleBaskets = () => {
  push('/warehouse/merchandiseOffers/merchandiseOffersBaskets')
}

// 控制编辑状态
const editingRowId = ref<string | null>(null)
const originalPrice = ref<string | null>(null) // 保存原始价格

// 激活编辑模式
const activateEdit = (row: any) => {
  editingRowId.value = row._nodeId
  originalPrice.value = row.price // 保存原始价格

  // 如果价格包含逗号，将输入框值置空
  if (row.price && String(row.price).includes(',')) {
    console.log('价格包含逗号，将输入框置空:', row.price)
    row.price = ''
  }

  // 下一帧自动聚焦输入框
  nextTick(() => {
    const inputEl = document.querySelector(`[data-row-id="${row._nodeId}"] input`)
    if (inputEl) {
      ;(inputEl as HTMLInputElement).focus()
      ;(inputEl as HTMLInputElement).select()
    }
  })
}

// 取消编辑模式
const deactivateEdit = () => {
  editingRowId.value = null
  originalPrice.value = null
}

// 根据层级设置行的CSS类名
const getRowClassName = ({ row }: { row: any }) => {
  const level = row._level
  switch (level) {
    case 0:
      return 'row-level-0' // 第一层：商品级别
    case 1:
      return 'row-level-1' // 第二层：虚拟仓级别
    case 2:
      return 'row-level-2' // 第三层：具体仓库级别
    default:
      return ''
  }
}

// 处理售价变更事件
const handlePriceChange = async (row: any, index: number) => {
  console.log('售价变更:', {
    rowData: row,
    index: index,
    newPrice: row.price,
    originalPrice: originalPrice.value,
    inventoryId: row.inventory_id,
    warehouseId: row.warehouse_id,
    level: row._level
  })

  // 检查价格是否发生变化
  if (String(row.price || '') === String(originalPrice.value || '')) {
    console.log('价格未变化，取消编辑模式')
    deactivateEdit()
    return
  }

  // 检查价格是否为空
  if (!row.price || String(row.price).trim() === '') {
    console.log('价格为空，恢复原始值并取消编辑模式')
    ElMessage.warning('请输入售价')
    // 恢复原始值
    row.price = originalPrice.value
    deactivateEdit()
    return
  }

  // 数据验证示例
  if (row.price && isNaN(Number(row.price))) {
    ElMessage.warning('请输入有效的数字')
    return
  }

  try {
    const res = await saveEditApi({
      warehouse_id: row.warehouse_id,
      fl_warehouse_id: row.fl_warehouse_id,
      inventory_id: row.inventory_id,
      is_futures: row.is_futures,
      productid: row.productid,
      arrival_date: row.arrival_date,
      price: row.price
    })
    if (res.code === 0) {
      ElMessage.success('售价已更新')
      // 取消编辑模式
      deactivateEdit()
      // 刷新列表
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    ElMessage.error('保存失败，请重试')
    console.error('保存售价失败:', error)
  }
}

// 取消编辑（ESC键或点击外部）
const handleCancelEdit = () => {
  deactivateEdit()
}

const expandedKeys = ref<any>([])
const toggleExpand = (row) => {
  const key = row._nodeId
  const index = expandedKeys.value.indexOf(key)
  if (index > -1) {
    expandedKeys.value.splice(index, 1) // 收起
  } else {
    // 可选：限制只展开一项
    // this.expandedKeys = [key];
    expandedKeys.value.push(key) // 展开
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      ref="searchRef"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="flex flex-items-center my-20px">
      <BaseButton type="primary" @click="handleImport">导入</BaseButton>
      <BaseButton type="primary" @click="handleExport">{{ t('action.exportFile') }}</BaseButton>
      <BaseButton type="primary" @click="handleBaskets">新增提篮子商品报价</BaseButton>
    </div>

    <!-- 列表展示区 - 采用卡片式布局更适合H5 -->
    <div class="" v-if="isMobile">
      <div
        v-for="(item, index) in dataList"
        :key="item._nodeId || index"
        class="mobile-card el-card mb-12px p-4px"
      >
        <!-- 主行：始终显示，可点击展开 -->
        <div class="card-section">
          <span class="card-label">商品名称:</span>
          <span>{{ item.cname }}</span>
        </div>
        <div class="card-main" @click="toggleExpand(item)" style="cursor: pointer">
          <div class="card-section">
            <span class="card-label">仓库:</span>
            <span class="flex items-center"
              >{{ item.warehouse_name }}
              <template v-if="item.children && item.children.length">
                <el-icon v-if="expandedKeys.includes(item._nodeId)"><ArrowDown /></el-icon>
                <el-icon v-else><ArrowRight /></el-icon>
              </template>
            </span>
          </div>
          <Field :shopInfo="item" :is_futuresList="is_futuresList" />
          <!-- 操作按钮（始终显示） -->
          <div class="card-section card-action pb-12px">
            <BaseButton
              type="primary"
              size="small"
              @click="handleJumpToEdit(item, 'merchandiseOffersEdit')"
            >
              编辑
            </BaseButton>
          </div>
        </div>

        <!-- 第二行：仅当展开时显示 -->
        <div v-if="expandedKeys.includes(item._nodeId)" class="card-children">
          <div v-for="child in item.children" :key="child._nodeId" class="child-row">
            <div class="card-section" @click="toggleExpand(child)">
              <span class="card-label">仓库:</span>
              <span
                >{{ child.warehouse_name }}
                <template v-if="child.children && child.children.length">
                  <el-icon v-if="expandedKeys.includes(child._nodeId)"><ArrowDown /></el-icon>
                  <el-icon v-else><ArrowRight /></el-icon>
                </template>
              </span>
            </div>
            <!-- 其他子字段... -->
            <Field :shopInfo="child" :is_futuresList="is_futuresList" />

            <!-- 操作按钮（始终显示） -->
            <div class="card-section card-action pb-12px">
              <BaseButton
                type="primary"
                size="small"
                @click="handleJumpToEdit(child, 'merchandiseOffersEdit')"
              >
                编辑
              </BaseButton>
            </div>

            <!-- 第三行：仅当展开时显示 -->
            <div v-if="expandedKeys.includes(child._nodeId)" class="card-children">
              <div v-for="ch in child.children" :key="ch._nodeId" class="child-row">
                <div class="card-section" @click="toggleExpand(ch)">
                  <span class="card-label">仓库:</span>
                  <span>{{ ch.warehouse_name }}</span>
                </div>
                <!-- 其他子字段... -->
                <Field :shopInfo="ch" :is_futuresList="is_futuresList" />
                <!-- 操作按钮（始终显示） -->
                <div class="card-section card-action pb-12px">
                  <BaseButton
                    type="primary"
                    size="small"
                    @click="handleJumpToEdit(ch, 'merchandiseOffersEdit')"
                  >
                    编辑
                  </BaseButton>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-table
      v-else
      :data="dataList"
      row-key="_nodeId"
      border
      :header-cell-style="{ textAlign: 'center' }"
      :tree-props="{ children: 'children' }"
      :row-class-name="getRowClassName"
    >
      <el-table-column
        prop="warehouse_name"
        label="仓库"
        align="left"
        header-align="center"
        min-width="100"
      />
      <el-table-column
        prop="cname"
        label="商品名称"
        align="center"
        :width="calculateColumnWidth(dataList, 'cname', 1, 8)"
      >
        <!-- 关键：使用 scoped slot + CSS 保留空格 -->
        <template #default="scope">
          <div style="white-space: pre-wrap">{{ scope.row.cname }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="hashrate" label="算力" width="80" />

      <el-table-column align="center" prop="is_futures" label="库存类型" width="80">
        <template #default="{ row }">
          {{ useEnumeratePicker(is_futuresList, row.is_futures) }}
        </template>
      </el-table-column>

      <el-table-column align="center" prop="arrival_date" label="到货日期" width="94" />

      <el-table-column align="center" prop="real_arrival_date" label="真实到货日期" width="100" />

      <el-table-column
        align="center"
        prop="quantity"
        label="库存汇总"
        sortable
        width="100"
        :sort-method="(a, b) => Number(a.quantity || 0) - Number(b.quantity || 0)"
      />
      <el-table-column align="center" prop="price" label="售价（美金）" />
      <el-table-column align="center" prop="first_leg_logistics_fee" label="头程物流费（美金）" />
      <el-table-column align="center" prop="remark" label="备注（美金）" />
      <el-table-column align="center" prop="price_rmb" label="售价（人民币）" />
      <el-table-column
        align="center"
        prop="first_leg_logistics_fee_rmb"
        label="头程物流费（人民币）"
      />
      <el-table-column align="center" prop="remark_rmb" label="备注（人民币）" />
      <el-table-column align="center" label="操作" width="70">
        <template #default="{ row }">
          <BaseButton
            type="primary"
            size="small"
            @click="handleJumpToEdit(row, 'merchandiseOffersEdit')"
          >
            编辑
          </BaseButton>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <Pagination
      :total="total"
      v-model:page="currentPage"
      v-model:limit="pageSize"
      @pagination="getList"
    />
    <!--    导入弹框-->
    <DialogImport ref="DialogImportRef" @refresh="getList" />

    <!--    编辑弹框-->
    <EditDialog
      v-model:visible="editDialogVisible"
      :edit-data="editData"
      @success="handleEditSuccess"
    />
  </ContentWrap>
</template>

<style scoped>
:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 2px;
}

/* 第二层：虚拟仓级别 - 浅绿色背景 */
:deep(.row-level-1) {
  background-color: #eef2f6 !important;
}

:deep(.row-level-1):hover {
  background-color: #e0f2fe !important;
}

/* 第三层：具体仓库级别 - 浅黄色背景 */
:deep(.row-level-2) {
  background-color: #e1e5ec !important;
}

:deep(.row-level-2):hover {
  background-color: #dcfce7 !important;
}

/* 售价只读状态样式 */
.price-readonly {
  display: flex;
  min-height: 24px;
  padding: 4px 8px;
  color: #606266;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s ease;
  align-items: center;
  justify-content: center;
}

.price-readonly:hover {
  color: #409eff;
  background-color: #f5f7fa;
  border: 1px dashed #409eff;
}

/* 空值状态的特殊样式 */
.price-readonly:empty::before {
  font-style: italic;
  color: #c0c4cc;
  content: '点击设置';
}

.card-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
